﻿using K9Nano.Application.Dtos;
using K9Nano.Dependency;
using K9Nano.Domain.Logging;
using K9Nano.Extensions;
using K9Nano.Logging;
using Microsoft.EntityFrameworkCore;

namespace K9Nano.Application.Logging;

internal class LogAppService(LogDbContext db) : ILogAppService, IScopedDependency
{
    public Task<int> DeleteAsync(DateTime from, DateTime to, CancellationToken cancellation = default)
    {
        return db.Logs.AsNoTracking().Where(a => a.CreatedAt >= from && a.CreatedAt <= to)
            .ExecuteDeleteAsync(cancellation);
    }

    public virtual async Task<PagedResultDto<ApiLogEntity>> QueryAsync(ApiLogPagedInput input,
       CancellationToken cancellation = default)
    {
        var predicate = input.GetPredicate();

        var query = db.Logs.AsNoTracking().WhereIf(predicate is not null, predicate!);

        var total = await query.CountAsync(cancellation);

        if (total <= 0)
        {
            return new PagedResultDto<ApiLogEntity>(0, []);
        }

        query = input.Sort(query);

        var items = await query.Skip(input.Skip())
            .Take(input.PageSize)
            .ToListAsync(cancellation);

        return new PagedResultDto<ApiLogEntity>(total, items);
    }
}